package com.xiaomuedu.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.xiaomuedu.common.model.User;
import com.xiaomuedu.kit.RecordKit;
/**
 * Record系列课程案例
 * @author 小木
 *
 */
public class RecordController extends Controller{
	public void index(){
		setAttr("users", Db.find("select * from user"));
		renderJsp("index.jsp");
	}
	/**
	 * 自己创建Record实例 set属性值后保存
	 */
	public void setsave(){
		setAttr("msg", "调用RecordController-setsave方法");
		Record log=new Record();
		log.set("content", "调用RecordController-setsave方法");
		log.set("createTime", new Date());
		boolean success=Db.save("log",log);
		setAttr("success", success);
		setAttr("record", log);
		renderJson();
	}
	/**
	 * 从请求中获取model 保存
	 */
	public void getsave(){
		String content=getPara("log.content");
		Record log=new Record();
		log.set("content", content);
		log.set("createTime", new Date());
		boolean success=Db.save("log",log);
		setAttr("msg", "调用RecordController-getsave方法");
		setAttr("success", success);
//		setAttr("record", log);
		renderJson();
	}
	private Record getRecord(String recordName){
		return  RecordKit.getRecord(recordName, getRequest());
	}
	/**
	 * 从请求中获得Record getRecord
	 * 表单操作
	 */
	public void getrecord(){
		setAttr("record",getRecord("user"));
		setAttr("msg", "调用RecordController-getrecord方法");
		renderJson();
	}
	
	
	/**
	 * 根据所有符合条件的
	 */
	public void find(){
		List<Record> users=Db.find("select * from user where name like '%小木%'");
		setAttr("users",users);
		setAttr("msg", "调用RecordController-find方法");
		renderJson();
	}
	/**
	 * 根据id查询唯一数据 一条结果
	 */
	public void findbyid(){
		setAttr("user", Db.findById("user",getPara(0)));
		setAttr("msg", "调用RecordController-findbyid方法");
		renderJson();
	}
	/**
	 * 根据根据id查询唯一数据 一条结果 但是被过滤了 只查询返回指定字段列
	 */
	public void findByIdLoadColumns(){
		setAttr("user", Db.findFirst("select "+getPara("columns")+" from user where id="+getPara("id") ));
		setAttr("msg", "调用RecordController-findByIdLoadColumns方法");
		renderJson();
	}
	/**
	 * 根据根据条件查询第一个
	 */
	public void findfirst(){
		setAttr("user", Db.findFirst("select * from user"));
		setAttr("msg", "调用RecordController-findfirst方法");
		renderJson();
	}
	/**
	 * 根据根据条件查询第一个
	 */
	public void findfirst2(){
		setAttr("user", Db.findFirst("select * from user where name=?","小木"));
		setAttr("msg", "调用RecordController-findfirst2方法");
		renderJson();
	}
	
	/**
	 * 普通set修改
	 */
	public void setupdate1(){
		Integer id=getParaToInt("id");
		String name=getPara("name");
		Record user=new Record();
		user.set("id", id);
		user.set("name", name);
		boolean success=Db.update("user", user);
		setAttr("success", success);
		setAttr("user", Db.findById("user",id));
		setAttr("msg", "调用RecordController-setupdate1方法");
		renderJson();
	}
	/**
	 * 根据id先get 后set修改
	 */
	public void setupdate2(){
		Integer id=getParaToInt("id");
		String name=getPara("name");
		Record user=Db.findById("user",id);
		if(user==null){
			setAttr("errorMsg", "id 无效");
		}else{
			user.set("name", name);
			boolean success=Db.update("user",user);
			setAttr("success", success);
		}
		setAttr("user",  Db.findById("user",id));
		setAttr("msg", "调用RecordController-setupdate2方法");
		renderJson();
	}
	
	/**
	 * 普通get修改
	 */
	public void getupdate(){
		Record user=getRecord("user");
		if(StrKit.isBlank(user.getStr("id"))){
			setAttr("errorMsg", "id无效");
		}else{
			boolean success=Db.update("user",user);
			setAttr("success", success);
		}
		setAttr("user", Db.findById("user",user.get("id")));
		setAttr("msg", "调用RecordController-setupdate方法");
		renderJson();
	}
	/**
	 * set-delete
	 */
	public void setdelete(){
		Integer id=getParaToInt(0);
		Record user=new Record();
		user.set("id",id);
		boolean success=Db.delete("user", user);
		//delete from user where id=?
		setAttr("success", success);
		Record record=Db.findById("user",id);
		setAttr("user", record==null?"已经被删除":"删除失败");
		setAttr("msg", "调用RecordController-setdelete方法");
		renderJson();
	}
	/**
	 * get-delete
	 */
	public void getdelete(){
		Integer id=getParaToInt(0);
		Record user=Db.findById("user",id);
		if(user==null){
			setAttr("errormsg", "id 无效");
		}else{
			boolean success=Db.delete("user", user);
			setAttr("success", success);
		}
		Record record=Db.findById("user",id);
		setAttr("user", record==null?"已经被删除":"删除失败");
		setAttr("msg", "调用RecordController-getdelete方法");
		renderJson();
	}
	/**
	 * delbyid
	 */
	public void delbyid(){
		Integer id=getParaToInt(0);
		boolean success=Db.deleteById("user",id);
		setAttr("success", success);
		Record record=Db.findById("user",id);
		setAttr("user", record==null?"已经被删除":"删除失败");
		setAttr("msg", "调用RecordController-delbyid方法");
		renderJson();
	}
	/**
     * 获取前端传来的数组对象并响应成Record列表
     *
     * @param recordName
     * @return
     */
    public   List<Record> getRecords(String recordName) {
        List<String> nos = getModelsNoList(recordName);
        List<Record> list =new ArrayList<Record>();
        for (String no : nos) {
        	Record m = getRecord(recordName + "[" + no + "]");
            if (m != null) {
                list.add(m);
            }
        }
        return list;
    }

    /**
     * 提取model对象数组的标号
     *
     * @param modelName
     * @return
     */
    protected List<String> getModelsNoList(String modelName) {
        // 提取下标
        List<String> list = new ArrayList<String>();
        String modelNameAndLeft = modelName + "[";
        Map<String, String[]> parasMap = getRequest().getParameterMap();
        for (Map.Entry<String, String[]> e : parasMap.entrySet()) {
            String paraKey = e.getKey();
            if (paraKey.startsWith(modelNameAndLeft)) {
                String no = paraKey.substring(paraKey.indexOf("[") + 1,
                        paraKey.indexOf("]"));
                if (!list.contains(no)) {
                    list.add(no);
                }
            }
        }
        Collections.sort(list);
        return list;
    }
	/**
	 * 获得多个model - save
	 */
	public void getrecordssave(){
		setAttr("olgCount",Db.queryLong("select count(*) from user"));
		//第一种
		List<Record> users=getRecords("user");
		for(Record user:users){
			user.set("sex", 1);
		}
		setAttr("得到users",users);
		Db.batchSave("user", users, users.size());
		//第二种  和model，record都没有关系，是最低层的用法
		/*String[] names=getParaValues("user.name");
		Integer[] ages=getParaValuesToInt("user.age");
		int len=names.length;
		Object[][] paras=new Object[len][3];
		for(int i=0;i<len;i++){
			paras[i][0]=names[i];
			paras[i][1]=ages[i];
			paras[i][2]=1;
		}
		Db.batch("insert into user(name,age,sex) values(?,?,?)", paras, len);*/
		setAttr("count",Db.queryLong("select count(*) from user"));
		setAttr("msg", "调用RecordController-getrecordssave方法");
		renderJson();
	}
	/**
	 * 批量获取与更新
	 */
	public void getrecordsupdate(){
		//第一种
		/*String[] ids=getParaValues("user.id");
		String[] names=getParaValues("user.name");
		Integer[] ages=getParaValuesToInt("user.age");
		int len=ids.length;
		Object[][] paras=new Object[len][3];
		for(int i=0;i<len;i++){
			paras[i][0]=ages[i];
			paras[i][1]=names[i];
			paras[i][2]=ids[i];
		}
		Db.batch("update user set age=?,name=? where id=?", paras, len);*/
		//第二种
		List<Record> users=getRecords("user");
		Db.batchUpdate("user",users, users.size());
		setAttr("users",Db.find("select id,name,age from user"));
		setAttr("msg", "调用RecordController-getrecordsupdate方法");
		renderJson();
	}
	/**
	 * 所有男变女
	 */
	public void updaterecords1(){
		Db.update("update user set sex=2 where sex=1");
		
		setAttr("users",Db.find("select * from user"));
		setAttr("msg", "调用RecordController-updaterecords1方法");
		renderJson();
	}
	/**
	 * 所有女变男
	 */
	public void updaterecords4(){
		Db.update("update user set sex=1 where sex=2");
		
		setAttr("users",Db.find("select * from user"));
		setAttr("msg", "调用RecordController-updaterecords4方法");
		renderJson();
	}
	/**
	 * 更新所有女年龄21
	 */
	public void updaterecords2(){
		Db.update("update user set age=21 where sex=2");
		setAttr("users",Db.find("select * from user"));
		setAttr("msg", "调用RecordController-updaterecords2方法");
		renderJson();
	}
	/**
	 * 更新所有名字带小木的年龄28
	 */
	public void updaterecords3(){
		Db.update("update user set age=28 where name like '%小木%'");
		setAttr("users",Db.find("select * from user"));
		setAttr("msg", "调用RecordController-updaterecords3方法");
		renderJson();
	}
	/**
	 * 多ID 批量删除
	 */
	public void batchdel(){
		Integer ids[]=getParaValuesToInt("id");
		if(ids==null||ids.length==0){
			setAttr("msg", "请选择要删除的数据");
		}else{
			//第一种
			/*Object[][] paras=new Object[ids.length][1];
			for(int i=0;i<ids.length;i++){
				paras[i][0]=ids[i];
			}
			Db.batch("delete from user where id=?",paras,ids.length);*/
			//第二种
//			for(int i=0;i<ids.length;i++){
//				Db.deleteById("user",ids[i]);
//				//Db.update("delete from user where id=?", ids[i]);
//			}
/*			//第三种
			String str=new String();
			for(int i=0;i<ids.length;i++){
				str+=ids[i];
				if(i<ids.length-1){
					str+=",";
				}
			}
			Db.update("delete from user where id in ("+str+")");
*/			//第四种
			String str=new String();
			for(int i=0;i<ids.length;i++){
				str+="?";
				if(i<ids.length-1){
					str+=",";
				}
			}
			Db.update("delete from user where id in ("+str+")",ids);
			setAttr("users",Db.find("select * from user"));
			setAttr("msg", "调用RecordController-batchdel方法");
		}
		renderJson();
	}
	/**
	 * 按条件批量删除 删除 小于18岁的女生
	 */
	public void batchdel2(){
		Db.update("delete from user where age<18 and sex=2");
		setAttr("users",Db.find("select * from user"));
		setAttr("msg", "调用RecordController-batchdel2方法");
		renderJson();
	}
	/**
	 * 删除所有名字带小木
	 */
	public void batchdel3(){
		Db.update("delete from user where name like '%小木%'");
		setAttr("users",Db.find("select * from user"));
		setAttr("msg", "调用RecordController-batchdel3方法");
		renderJson();
	}
	/**
	 * model转record
	 */
	public void modeltorecord(){
		User user=new User();
		user.set("name", "model转record");
		user.set("sex", 1);
		user.set("age", 1);
		user.set("remark", "model转record");
		
		Record record=user.toRecord();
		Db.save("user", record);
		
		setAttr("users",Db.find("select * from user"));
		setAttr("msg", "调用RecordController-modeltorecord方法");
		renderJson();
	}
	/**
	 * model转record
	 */
	public void recordtomodel(){
		Record user=new Record();
		user.set("name", "record转model");
		user.set("sex", 1);
		user.set("age", 1);
		user.set("remark", "record转model");
		User model=new User();
		model._setAttrs(user.getColumns());
		model.save();
		setAttr("users",Db.find("select * from user"));
		setAttr("msg", "调用RecordController-modeltorecord方法");
		renderJson();
	}
}
